<template>
  <div class="container">
    <div class="title">基本信息</div>
    <Information ref="Information" :formObj.async="formObj" :type="type" :date="date" :maxValue="maxValue" :reqOrgNo="reqOrgNo" />
    <div class="title">监测运行情况</div>
    <Monitor ref="monitor" :select-obj="selectObj" :type="type" :date="date" :maxValue="maxValue" :reqOrgNo="reqOrgNo" />
    <div class="title">报送情况</div>
    <Report ref="report" :type="type" :select-obj="selectObj" :date="date" :maxValue="maxValue" :reqOrgNo="reqOrgNo" />
    <div class="title">外部情况及管理动作</div>
    <External ref="external" :select-obj="selectObj" :type="type" :date="date" :maxValue="maxValue" :reqOrgNo="reqOrgNo" />

    <template v-if="type === 'edit'">
      <div class="title" style="margin-bottom: 10px;">修改原因</div>
      <bfe-input v-model="remark" type="textarea" :rows="3" :placeholder="$t('stm.common.pleaseInput')"
        :maxlength="10000"></bfe-input>
    </template>
    <template v-if="type !== 'add' && operationList.length > 0">
      <div class="title" style="margin-bottom: 10px;">操作日志</div>
      <bfe-table :data="operationList" border style="width: 100%" :height="300">
        <bfe-table-column prop="usrRefno" label="用户编号"></bfe-table-column>
        <bfe-table-column prop="usnm" label="用户名称"></bfe-table-column>
        <bfe-table-column prop="optDesc" label="操作描述"></bfe-table-column>
        <bfe-table-column prop="optTime" label="操作时间" width="180"></bfe-table-column>
      </bfe-table>
      <bfe-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="tablePage.pageNo" :page-size="tablePage.pageSize"
        layout="total, prev, pager, next, jumper" :total="tablePage.total" />
    </template>
    <div style="margin-top: 10px;">
      <bfe-button @click="goBack">返回</bfe-button>
      <bfe-button v-if="type !== 'view'" type="primary" @click="onAdd">提交</bfe-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import mixin from "@/views/business/stm/mixins";
import Information from "./information";
import Monitor from "./monitor.vue";
import Report from "./report";
import External from "./external.vue";
import _ from 'lodash';

export default {
  components: {
    Information,
    Monitor,
    Report,
    External,
  },
  mixins: [mixin],
  props: {
    headId: {
      type: String,
      default: "",
    },
    date: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: "add",
    },
    handlePageType: {
      type: Function,
      default: () => { },
    },
    selectObj: {
      type: Object,
      default: () => { },
    },
    reqOrgNo: {
      type: String,
      default: null,
    }
  },
  data() {
    return {
      formObj: {
        rptOrgNo: "",
        rptOrgName: "",
        rptpd: "",
        rptPer: "",
        cntel: "",
        email: "",
      },
      remark: "",
      operationList: [],
      // 分页
      tablePage: {
        pageNo: 1,
        pageSize: 5,
        total: 0,
      },
      maxValue: 2147483647, // 检验输入的最大值
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.base.userInfo,
    }),
  },
  created() {
    this.getOperationData()
  },
  methods: {
    goBack() {
      this.handlePageType("home");
    },
    getOperationData() {
      // 查询操作日志只在edit || view
      if (this.type !== 'add') {
        const params = {
          optCode: 'STM002GET1813',
          payload: {
            headId: this.headId,
            rptOrgNo: this.reqOrgNo,
            rptpd: this.date,
          },
          pageInfo: {
            pageNo: this.tablePage.pageNo,
            pageSize: this.tablePage.pageSize
          }
        }
        this.$p2svr(
          this.$api["_01_TSTM02MONRPT1800"],
          "RequestPoAuth",
          params
        ).then((res) => {
          //console.log(res, "打印操作日志的结果");
          this.operationList = res.payload
          this.tablePage.total = res.pageInfo ? res.pageInfo.total : 0
          this.tablePage.pageNo = res.pageInfo ? res.pageInfo.pageNo : 1
          this.tablePage.pageSize = res.pageInfo ? res.pageInfo.pageSize : 5
        });
      }
    },
    /* handleSizeChange(val) {
      this.tablePage.pageSize = val
      this.getOperationData()
    },*/
    /*handleCurrentChange(val) {
      this.tablePage.pageNo = val
      this.getOperationData()
    },*/
    handleSizeChange: _.debounce(function(val) {
      const self = this
      self.tablePage.pageSize = val
      return self.getOperationData()
    }, 300),
    handleCurrentChange: _.debounce(function(val) {
      const self = this
      self.tablePage.pageNo = val
      return self.getOperationData()
    }, 300),
    filterObjects(arr) {
      return arr.filter(obj => {
        // 遍历对象的所有自身属性
        for (let key in obj) {

          if (obj.hasOwnProperty(key)) {
            // 跳过 sn 字段
            if (key === 'sn') continue;

            const value = obj[key];
            // 检查值是否非空（非 null, undefined, 空字符串）
            if (value !== null && value !== undefined && value !== '') {
              return true; // 只要有一个有效值，保留对象
            }
          }
        }
        // 所有非 sn 字段都为空或 null，过滤掉这个对象
        return false;
      });

    },
    onAdd() {
      // 校验
      const validateArr = ['Information', 'monitor', 'report']
      const flagArr = validateArr.map(val => this.$refs[val].validateForm())
      if (flagArr.includes(false)) {
        return
      }
      const monitorData = this.$refs.monitor && this.$refs.monitor?.formObj;
      //console.log(monitorData,"monitorData")
      const modlListListClone = this.$refs.monitor && this.$refs.monitor?.modlListListClone;
      const modlOprtInfoStatListClone = this.$refs.monitor && this.$refs.monitor?.modlOprtInfoStatListClone;
      //console.log(modlListListClone,"提交modlListListClone")
      //console.log(modlOprtInfoStatListClone,"提交modlOprtInfoStatListClone")
      const reportData = this.$refs.report && this.$refs.report?.formObj?.list;
      const externalData = this.$refs.external && this.$refs.external?.list;
      const params = {
        // 有id是修改没有是新增
        optCode: "STM002MOD1813",
        payload: {
          ...this.formObj,
          optType: this.type === "add" ? 1 : 2,
          prjTsqList: monitorData.prjTsqList ? monitorData.prjTsqList : [],
          modlListList:
                  modlListListClone &&
                  modlListListClone.map((item) => {
              return {
                modlRefno: item.modlRefno,
                modlName: item.modlName,
                modlDes: item.modlDes,
                oprtSts: item.oprtSts,
              };
            }),
          modlOprtInfoStatList:
                  modlOprtInfoStatListClone &&
            this.filterObjects(modlOprtInfoStatListClone.map((item, index) => {
              return {
                sn: index + 1,
                modlRefno: item.modlRefno,
                modlName: item.modlName,
                warnAmot: item.warnAmot,
                complChkQanty: item.complChkQanty,
                cfmSspcsQanty: item.cfmSspcsQanty,
              };
            })),
          sspcsSbmsnStatList:
            reportData &&
            reportData.map((item) => {
              return {
                ...item,
                cnrrd: item.cnrrd ? String(item.cnrrd) : '',
              };
            }),
          infoAndMagList: externalData ? this.filterObjects(externalData.map((item, index) => {
            return {
              sn: index + 1,
              ...item
            };
          })) : [],
        },
      };

      if (this.type === 'edit') {
        if (!this.remark) {
          this.$message.error("请输入修改意见");
          return
        }
      }
      params.payload.remark = this.type === 'edit' ? this.remark : '新增'
      this.$p2svr(
        this.$api["_01_TSTM02MONRPT1800"],
        "RequestPoAuth",
        params
      ).then((res) => {
        //console.log(res, "打印提交的结果");
        if (res.errCode !== 'error') {
          this.$message.success(this.type === "add" ? "新增成功" : "编辑成功");
          this.handlePageType("home");
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.container {
  background-size: 100% 100%;

  .title {
    font-size: 26px;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 6px;

    &::before {
      content: "";
      width: 4px;
      height: 24px;
      background: #d21f3e;
      flex-shrink: 0; // 防止被压缩
    }
  }
}
</style>